﻿using LitJson;
using System.ComponentModel;

namespace Model
{
    public static class JsonHelper
    {
        /// <summary>
        /// 从字符串到VersionConfig配置
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static VersionConfig FromString(string json)
        {
            JsonData jsonData = JsonMapper.ToObject(json);

            VersionConfig versionConfig = new VersionConfig();
            ISupportInitialize supportInitialize = versionConfig as ISupportInitialize;

            if (supportInitialize != null)
            {
                supportInitialize.EndInit();
            }

            versionConfig.Version = int.Parse(jsonData["Version"].ToString());
            versionConfig.TotalSize = long.Parse(jsonData["TotalSize"].ToString());

            foreach (JsonData item in jsonData["FileVersionInfos"])
            {
                versionConfig.FileVersionInfos.Add(new FileVersionInfo
                {
                    File = item["File"].ToString(),
                    MD5 = item["MD5"].ToString(),
                    Size = long.Parse(item["Size"].ToString())
                });
            }

            if (supportInitialize != null)
            {
                supportInitialize.EndInit();
            }
            return versionConfig;
        }

        public static string ToJson(this VersionConfig versionConfig)
        {
            ISupportInitialize supportInitialize = versionConfig as ISupportInitialize;
            if (supportInitialize != null)
            {
                supportInitialize.EndInit();
            }

            JsonWriter jsonWriter = new JsonWriter();
            jsonWriter.WriteObjectStart();
            jsonWriter.WritePropertyName("Version");
            jsonWriter.Write(versionConfig.Version);
            jsonWriter.WritePropertyName("TotalSize");
            jsonWriter.Write(versionConfig.TotalSize);

            jsonWriter.WritePropertyName("FileVersionInfos");
            jsonWriter.WriteArrayStart();
            foreach (FileVersionInfo item in versionConfig.FileVersionInfos)
            {
                jsonWriter.WriteObjectStart();

                jsonWriter.WritePropertyName("MD5");
                jsonWriter.Write(item.MD5);

                jsonWriter.WritePropertyName("File");
                jsonWriter.Write(item.File);

                jsonWriter.WritePropertyName("Size");
                jsonWriter.Write(item.Size);

                jsonWriter.WriteObjectEnd();
            }
            jsonWriter.WriteArrayEnd();

            jsonWriter.WriteObjectEnd();
            return jsonWriter.ToString();
        }
    }
}
